<?php
declare(strict_types=1);
namespace Service\QueryService;
use Service\BaseService;
use Service\Code\Normal;
use App\Model\PssModel\Business;
use App\Model\PssLogModel\MessageSkuChangeLog;
use Service\AppService\SystemCacheConfigService;
use App\Model\PssLogModel\MessageUserSkuChangeLog;

/**
 * 查询用户渠道商品变更日志
 */
class QueryUserChangeGoodsLogService extends BaseService
{
    /**
     * 查询平行云仓数据
     * @param array $param
     */
    public function queryChildYcGoodsLog(array $param)
    {
        if( empty($param['appid']) ) {
            return Normal::returnCode(Normal::FAIL,"appid参数缺失");
        }
        
        $user = Business::instance()->info(['appid'=>$param['appid']]);
        if( empty($user) ) {
            return Normal::returnCode(Normal::FAIL,"渠道用户信息不存在");
        }
        
        //获取要系统获取数据条数限制
        $config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('channel_task_user_limit');
        $taskUserQueryGoodsLogCount = !empty($config['TaskUserQueryGoodsLogCount']) ? $config['TaskUserQueryGoodsLogCount'] : 10;
        $taskUserQueryGoodsLogCount = (int)$taskUserQueryGoodsLogCount;
        
        $bid = (int)$user['id'];
        $list = MessageSkuChangeLog::instance()
        ->select(['id','message_type','contents'])
        ->where('bid',$bid)
        ->orderBy('id','asc')
        ->limit($taskUserQueryGoodsLogCount)
        ->get()
        ->toArray();
        
        if( empty($list) ) {
            return Normal::returnCode(Normal::FAIL,"当前渠道没有增量更新的商品日志需要处理!");
        }
        
        $logIds = array_column($list,'id');
        $saveDataAll = [];
        foreach ($list as $item)
        {
            $saveData = $this->handleUserSkuChangeLog($user,$item['contents']);
            if( !empty($saveData) ) {
                $saveDataAll = array_merge($saveDataAll,$saveData);                
            }
        }
        
        //如果有日志数据，则开始批量写入
        if( !empty($saveDataAll) ) 
        {
            MessageSkuChangeLog::instance()->whereIn('id',$logIds)->delete();
            MessageUserSkuChangeLog::instance()->insert($saveDataAll);
        }
        
        return Normal::returnCode(Normal::SUC,"获取成功",$list);
    }
    
    /**
     * 组装批量数据
     * @param array $user
     * @param string $contents
     */
    public function handleUserSkuChangeLog( array $user,string $contents)
    {
        $bid            = $user['id'];
        $push_url       = $user['open_url'];
        $push_result    = json_encode(Normal::returnCode(Normal::SUC,"处理成功"),JSON_UNESCAPED_UNICODE);
        $contentsArr    = @json_decode($contents, true);
        $data           = $contentsArr['data'];
        $soure          = $contentsArr['Source'] ?? 1;
        $message_type   = $contentsArr['MessageType'] ?? '';
        $created_at     = date('Y-m-d H:i:s');
        $saveData       = [];
        if( $message_type == 'goodsSkuChange' )//商品下架
        {
            //商品下架
            $skuList = $data['skuList'];
            foreach ($skuList as $value)
            {
                $tempGoods = $data;
                $tempGoods['skuList'] = [$value];
                $saveData[] = [
                    'source'        => $soure,
                    'bid'           => $bid,
                    'skucode'       => $value,
                    'contents'      => json_encode($tempGoods,JSON_UNESCAPED_UNICODE),
                    'message_type'  => $message_type,
                    'created_at'    => $created_at,
                    'push_url'      => $push_url,
                    'push_status'   => 1,
                    'push_result'   => $push_result,
                    'used_time'     => '0.000'
                ];
            }
        } 
        else if( $message_type == 'goodsChange' ) 
        {//商品更改
            foreach ($data as $goodsItem)
            {
                foreach ($goodsItem['skuList'] as $skuItem)
                {
                    $tempGoods = $goodsItem;
                    $tempGoods['skuList'] = [$skuItem];
                    $saveData[] = [
                        'source'        => $soure,
                        'bid'           => $bid,
                        'skucode'       => $skuItem['skucode'],
                        'contents'      => json_encode($tempGoods,JSON_UNESCAPED_UNICODE),
                        'message_type'  => $message_type,
                        'created_at'    => $created_at,
                        'push_url'      => $push_url,
                        'push_status'   => 1,
                        'push_result'   => $push_result,
                        'used_time'     => '0.000'
                    ];
                }
            }
        } 
        else 
        {//其它类型
            $saveData[] = [
                'bid'           => $bid,
                'skucode'       => '0',
                'contents'      => $contents,
                'message_type'  => $message_type,
                'created_at'    => $created_at,
                'push_url'      => $push_url,
                'push_status'   => 1,
                'push_result'   => $push_result,
                'used_time'     => '0.000'
            ];
        }
    
        return $saveData;
    }
}